package com.omesoft.hksnore.monitoring;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfcImpl;
import com.omesoft.hksnore.util.data.DensityUtil;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.data.UserUtil;
import com.omesoft.hksnore.util.myactivity.BaseFragment;
import com.omesoft.hksnore.util.omeview.MyGirdView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Omesoft on 2017/3/13.
 */
@SuppressLint("ValidFragment")
public class CalendarSelectFragment extends BaseFragment {
    private final int DATABEAN_TYPE_UNVISIBLE = -1;
    private final int DATABEAN_TYPE_WEEKSTR = 0x01;
    private final int DATABEAN_TYPE_CLICKABLE = 0x02;
    private final int DATABEAN_TYPE_UNCLICKABLE = 0x03;

    private int GIRDVIEW_ITEM_HEIGHT;

    private String TAG = "CalendarSelectFragment";
    /**
     * 所选中的日期，如：2015-08-08
     */
    public static String selectDate = null;
    private View rootView;
    private MyGirdView girdView;
    private CalendarSelectGirdViewAdapter adapter;

    private List<DataBean> dataBeans;
    private String thisDate = null;// 记录本月份
    private int thisYear, thisMonth;
    private int selectedYear, selectedMonth, selectedDay;
    private boolean isSelectedThis = false;// 记录是否选中了本页面所显示月份的日期
    private int girdviewHeight;

    private MendaleSleepAllIfcImpl ifc;

    private Handler mainHandler;

    /**
     * @param date
     *            年份和月份，20XX-xx
     */
    public CalendarSelectFragment(String date, Handler handler) {
        try {
            mainHandler = handler;
            // date = "2015-07";
            thisDate = date;
            String[] str = date.split("-");
            thisYear = Integer.parseInt(str[0]);
            thisMonth = Integer.parseInt(str[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        rootView = inflater.inflate(R.layout.fragment_monitor_calendar_select, container, false);
        init();
        initHandler();
        initView();
        loadView();
        return rootView;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (selectDate != null) {
            String[] str = selectDate.split("-");
            selectedYear = Integer.parseInt(str[0]);
            selectedMonth = Integer.parseInt(str[1]);
            selectedDay = Integer.parseInt(str[2]);
            if (selectedYear == thisYear && selectedMonth == thisMonth) {
                isSelectedThis = true;
            } else
                isSelectedThis = false;
        } else {
            isSelectedThis = false;
        }
        // sendMsg2Main(MonitorCalendarSelectActivity.HANDLER_SET_VIEWPAGER_HEIGHT,
        // girdviewHeight);
        // sendMsg2Main(MonitorCalendarSelectActivity.HANDLER_SET_CALENDAR_MONTH,
        // thisDate);
    }


    protected void init() {
        // TODO Auto-generated method stub

        // 35是单个item高度
        // 15是item与底部的距离
        // 2是整个gridview与底部的距离

        GIRDVIEW_ITEM_HEIGHT = DensityUtil.dip2px(getActivity(), 35 +8 + 2);
        dataBeans = new ArrayList<DataBean>();
        ifc = new MendaleSleepAllIfcImpl(context);
        SparseArray<Boolean> array = ifc.findDayByMonth(MySharedPreferencesUtil.getMemberId(context), thisDate);
        Log.v(TAG, "array::" + array.toString());
        initDay(array);
        array.clear();
        array = null;
    }

    @Override
    protected void initView() {
        // TODO Auto-generated method stub
        super.initView();
        girdView = (MyGirdView) rootView.findViewById(R.id.fragment_calendar_select_girdview);
    }

    @Override
    protected void loadView() {
        // TODO Auto-generated method stub
        super.loadView();
        adapter = new CalendarSelectGirdViewAdapter();
        girdView.setAdapter(adapter);
        setGridViewHeight();
        girdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                DataBean bean = dataBeans.get(arg2);
                if (bean.type == DATABEAN_TYPE_CLICKABLE) {
                    int tempDay = Integer.parseInt(bean.str);
                   // if (tempDay != selectedDay) {//决定已选中的日期是否可以点击
                        selectedDay = tempDay;
                        adapter.notifyDataSetChanged();
                        String tempMonth = thisMonth < 10 ? "0" + thisMonth : String.valueOf(thisMonth);
                        String tempDayStr = tempDay < 10 ? "0" + tempDay : String.valueOf(tempDay);
                        String date = thisYear + "-" + tempMonth + "-" + tempDayStr;
                        sendMsg2Main(MonitorCalendarSelectActivity.HANDLER_FINISH, date);
                    //}
                }
            }
        });
    }

    @Override
    protected void initHandler() {
        // TODO Auto-generated method stub
        super.initHandler();
    }

    private void setGridViewHeight() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) girdView.getLayoutParams();
        params.height = girdviewHeight;
        girdView.setLayoutParams(params);
    }

    private void sendMsg2Main(int msg, Object obj) {
        Message message = Message.obtain();
        message.what = msg;
        message.obj = obj;
        mainHandler.sendMessage(message);
    }

    public int getGridViewHeight() {
        return girdviewHeight;
    }

    public String getTitle() {
        if (UserUtil.isZh(context)) {
            return thisYear + "年" + (thisMonth >= 10 ? thisMonth : "0" + thisMonth) + "月";
        } else {
            return thisYear + "-" + (thisMonth >= 10 ? thisMonth : "0" + thisMonth);
        }

    }

    /**
     * 加载日期数据
     */
    private void initDay(SparseArray<Boolean> array) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, thisYear);
        a.set(Calendar.MONTH, thisMonth - 1);// 月份要-1
        a.set(Calendar.DATE, 1);
        a.setFirstDayOfWeek(Calendar.MONDAY);
        // Log.v(TAG, "月::" + String.valueOf(a.get(Calendar.MONTH) + 1));
        // Log.v(TAG, "日::" + a.get(Calendar.DATE));
        // Log.v(TAG, "星期总数::" + a.getActualMaximum(Calendar.WEEK_OF_MONTH));
        // Log.v(TAG, "天数::" + a.getActualMaximum(Calendar.DAY_OF_MONTH));
        // Log.v(TAG, "星期::" + String.valueOf(a.get(Calendar.DAY_OF_WEEK) - 1));
        int allWeek = a.getActualMaximum(Calendar.WEEK_OF_MONTH);
        int allDay = a.getActualMaximum(Calendar.DAY_OF_MONTH);
        int firstDayOfWeek = a.get(Calendar.DAY_OF_WEEK) - 1;
        if (firstDayOfWeek <= 0)
            firstDayOfWeek = 7;
        int length = (allWeek + 1) * 7;
        // String[] weekString = new String[] { "周一", "周二", "周三", "周四", "周五",
        // "周六", "周日" };
        String[] weekString = getResources().getStringArray(R.array.weekend);
        Log.v(TAG, "length::" + length);
        int day = 1;
        boolean isSetFirst = false;// 是否设置好了第一天
        for (int i = 0; i < length; i++) {
            DataBean bean = new DataBean();
            if (i >= 0 && i <= 6) {// 设置星期
                // bean.type = DATABEAN_TYPE_WEEKSTR;
                // bean.str = weekString[i];
            } else {
                if ((i - 7) == (firstDayOfWeek - 1)) {
                    bean.str = String.valueOf(day);
                    day++;
                    isSetFirst = true;
                } else {
                    if (isSetFirst) {
                        if (day <= allDay) {
                            bean.str = String.valueOf(day);
                            day++;
                        } else {
                            bean.str = null;
                            bean.type = DATABEAN_TYPE_UNVISIBLE;
                        }
                    } else {
                        bean.str = null;
                        bean.type = DATABEAN_TYPE_UNVISIBLE;
                    }
                }
                if (bean.type == 0) {// 0为初始化值，表示未定义
                    if (array.get(Integer.parseInt(bean.str), false)) {
                        bean.type = DATABEAN_TYPE_CLICKABLE;// 表示有数据
                    } else {
                        bean.type = DATABEAN_TYPE_UNCLICKABLE;// 无数据
                    }
                }

                dataBeans.add(bean);
                // Log.v(TAG, "bean::" + bean.toString());
            }

        }
        girdviewHeight = (allWeek + 1) * GIRDVIEW_ITEM_HEIGHT;
    }

    private class CalendarSelectGirdViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return dataBeans.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return dataBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.monitor_item_calendar_select, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.item_calendar_select_image);
                holder.text = (TextView) convertView.findViewById(R.id.item_calendar_select_text);
                holder.weekText = (ImageView) convertView.findViewById(R.id.item_calendar_unselect);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DataBean bean = dataBeans.get(position);
            holder.text.setText(bean.str);
            if (isSelectedThis && bean.type != DATABEAN_TYPE_UNVISIBLE && bean.type != DATABEAN_TYPE_WEEKSTR && (Integer.parseInt(bean.str) == selectedDay)) {
                holder.setSelected();
            } else {
                switch (bean.type) {
                    case DATABEAN_TYPE_UNVISIBLE:
                        holder.setUnvisible();
                        break;
                    case DATABEAN_TYPE_WEEKSTR:
                        // holder.setWeekTextVisivle();
                        // holder.weekText.setText(bean.str);
                        break;
                    case DATABEAN_TYPE_CLICKABLE:
                        holder.setClickable();
                        holder.text.setText(bean.str);
                        break;
                    case DATABEAN_TYPE_UNCLICKABLE:
                        holder.setUnClickable();
                        holder.text.setText(bean.str);
                        break;
                    default:
                        holder.setUnvisible();
                        break;
                }
            }
            return convertView;
        }

    }

    private class ViewHolder {
        public ImageView image,weekText;
        public TextView text ;

        public void setClickable() {
       //     image.setImageResource(R.mipmap.image_monitor_cldr_select_nomal);
            text.setTextColor(getResources().getColor(R.color.white));
            image.setVisibility(View.VISIBLE);
            text.setVisibility(View.VISIBLE);
            weekText.setVisibility(View.VISIBLE);
        }

        public void setUnClickable() {
        //    image.setImageResource(R.mipmap.image_monitor_calendar_select_unclickable);
            text.setTextColor(getResources().getColor(R.color.white));
            image.setVisibility(View.GONE);
            text.setVisibility(View.VISIBLE);
            weekText.setVisibility(View.GONE);
        }

        public void setSelected() {
            image.setImageResource(R.mipmap.calendar_select);
            text.setTextColor(getResources().getColor(R.color.white));
            image.setVisibility(View.VISIBLE);
            text.setVisibility(View.VISIBLE);
            weekText.setVisibility(View.GONE);
        }

        public void setWeekTextVisivle() {
            image.setVisibility(View.GONE);
            text.setVisibility(View.GONE);
            weekText.setVisibility(View.VISIBLE);
            weekText.setBackgroundColor(Color.parseColor("#ececec"));
        }

        public void setUnvisible() {
            image.setVisibility(View.GONE);
            text.setVisibility(View.GONE);
            weekText.setVisibility(View.GONE);
        }
    }

    private class DataBean {
        int type = 0;// 记录是星期文字、可点击、不可点击
        String str = null;

        @Override
        public String toString() {
            return "DataBean [type=" + type + ", str=" + str + "]";
        }
    }
}
